/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-12-23 14:05:56
 * @LastEditors: cgt
 * @LastEditTime: 2021-12-28 18:53:36
 */
function getFirstPosX(geometry) {
  if (Array.isArray(geometry)) {
    return getFirstPosX(geometry[0]);
  }
  return geometry;

}

function isWebMercator(num) {
  return num > 180 || num < -180;
}

/**
 * 判断当前数据是否是点坐标
 * @param {Object} data 判断数据
 */
function isPoint(data) {
  return Array.isArray(data) && !Array.isArray(data[0]);
}


/**
 * 坐标转换
 * @param {Array} coordinates 坐标集合
 * @param {Function} project 转换方法
 */
function projectCoordinates(coordinates, project) {
  var result = [];
  if (!isPoint(coordinates)) {
    for (let i = 0; i < coordinates.length; i++) {
      const coordinate = coordinates[i];
      result.push(projectCoordinates(coordinate, project));
    }
  } else {
    result = project(coordinates);
  }
  return result;
}
/**
 * 转换到墨卡托坐标系
 * @param {Array} lngLat [lng, lat]
 */
export function projectLngLatToWebMercator(geometry) {
  var firstPosX = getFirstPosX(geometry);
  if (isWebMercator(firstPosX)) {
    return geometry;
  }
  function project(lngLat) {
    var R = 6378137;
    var MAX_LATITUDE = 85.0511287798;

    var d = Math.PI / 180,
      max = MAX_LATITUDE,
      lat = Math.max(Math.min(max, lngLat[1]), -max),
      sin = Math.sin(lat * d);
    return [R * lngLat[0] * d, R * Math.log((1 + sin) / (1 - sin)) / 2];
  }

  return projectCoordinates(geometry, project);
}

/**
 * 转换到经纬度坐标系
 * @param {Array} xy [x, y]
 */
export function projectWebMercatorToLngLat(geometry) {
  var firstPosX = getFirstPosX(geometry);
  if (!isWebMercator(firstPosX)) {
    return geometry;
  }
  function project(xy) {
    var R = 6378137;
    var d = 180 / Math.PI;
    return [xy[0] * d / R, (2 * Math.atan(Math.exp(xy[1] / R)) - Math.PI / 2) * d];
  }

  return projectCoordinates(geometry, project);
}
